namespace HZY.Shared.Admin.MessageHandler;

/// <summary>
/// write log
/// </summary>
public class WriteLogHandler : IBus<SysOperationLog>
{
    public string topic => "WriteInLog";

    private static readonly ConcurrentBag<SysOperationLog> InsertList = [];
    private static readonly object Lock = new();

    private readonly IRepository<SysOperationLog> _sysOperationLogRepository;

    public WriteLogHandler(IRepository<SysOperationLog> sysOperationLogRepository)
    {
        _sysOperationLogRepository = sysOperationLogRepository;
    }

    public async Task HandlerAsync(SysOperationLog data)
    {
        lock (Lock)
        {
            if (InsertList.Count > 200)
            {
                _sysOperationLogRepository.InsertRange(InsertList.ToList());
                InsertList.Clear();
            }

            InsertList.Add(data);
        }

        await Task.CompletedTask;
    }

    /// <summary>
    /// 2min / InsertList
    /// </summary>
    [Scheduled("0 0/2 * * * ?", remark: "2min / InsertList")]
    public string Run()
    {
        lock (Lock)
        {
            _sysOperationLogRepository.InsertRange(InsertList.ToList());

            InsertList.Clear();
        }

        return "ok";
    }
}